package cn.mldn.microboot.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * description:
 * Created by gy on 2017/8/23.
 */

public class RedisObjectSerializer implements RedisSerializer<Object>{

    private static final byte[] EMPTY_BYTE_ARRAT = new byte[0];
    private Converter<Object,byte[]> serializingConverter = new SerializingConverter();
    private Converter<byte[],Object> deserializingConverter = new DeserializingConverter();

    @Override
    public byte[] serialize(Object o) throws SerializationException {
        if(null == o){
            return EMPTY_BYTE_ARRAT;
        }
        return this.serializingConverter.convert(o);
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if(null == bytes || 0 == bytes.length){
            return null;
        }
        return this.deserializingConverter.convert(bytes);

    }
}
